package com.alawn.framework.core.component;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@Component
public class CaptchaService {

	@Autowired
	private Producer producer;

	public StreamedContent createCaptcha(HttpServletRequest request) {
		StreamedContent graphicText = null;
		try {
			HttpSession session = request.getSession();
			String capText = producer.createText();
			BufferedImage capImg = producer.createImage(capText);

			ByteArrayOutputStream os = new ByteArrayOutputStream();

			ImageIO.write(capImg, "png", os);
			graphicText = new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()), "image/png");
			session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return graphicText;
	}

	public static boolean validateCaptcha(HttpServletRequest request, String value) {
		HttpSession session = request.getSession();
		String capText = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
		if (StringUtils.isBlank(capText) || StringUtils.isBlank(value)) {
			return false;
		}
		if (capText.equals(value)) {
			return true;
		}
		return false;
	}
}
